﻿using System.IdentityModel.Tokens.Jwt;
using System.Net.Http.Headers;
using System.Text;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
using StudyCompanion.Commons.Authorize;
using StudyCompanion.Dto.Chat;
using StudyCompanion.IServices;

namespace StudyCompanion.WebApi;

/// <summary>
/// </summary>
[Authorize]
public class MessageHub : Hub
{
    private readonly IHttpContextAccessor _httpContextAccessor;
    private readonly IUserService _userService;

    /// <summary>
    /// </summary>
    /// <param name="httpContextAccessor"></param>
    /// <param name="userService"></param>
    public MessageHub(IHttpContextAccessor httpContextAccessor
        , IUserService userService)
    {
        _httpContextAccessor = httpContextAccessor;
        _userService = userService;
    }

    public override async Task OnConnectedAsync()
    {
        string token = _httpContextAccessor.HttpContext.Request.Query["access_token"];
        if (string.IsNullOrEmpty(token))
        {
            await base.OnDisconnectedAsync(null);
            return;
        }
        var jwtToken = new JwtSecurityTokenHandler().ReadJwtToken(token);
        var userId = jwtToken.Claims.First(x => x.Type == ClaimConst.UserId).Value;
        await Groups.AddToGroupAsync(Context.ConnectionId, userId);
        await base.OnConnectedAsync();
    }

    /// <summary>
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task Query(string input)
    {
        string token = _httpContextAccessor.HttpContext.Request.Query["access_token"];
        var jwtToken = new JwtSecurityTokenHandler().ReadJwtToken(token);
        var userId = jwtToken.Claims.First(x => x.Type == ClaimConst.UserId).Value;

        Console.WriteLine($"用户（{userId}）的提问：{input}");
        var user = await _userService.GetUserbyId(long.Parse(userId));
        if (user.Item2.ValidTime < DateTime.Now)
        {
            await Clients.Group(userId).SendAsync("error", "10001");
            return;
        }
        var client = new HttpClient();
        var uri = new Uri("http://admin.qidian22.com/Chat/Home/query");
        using var request = new HttpRequestMessage(HttpMethod.Post, uri);
        request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/event-stream"));
        var dto = new ChatGPTQueryDto { UserId = 1, Query = "你好" };
        var content = JsonContent.Create(dto);
        request.Content = content;
        var response = client.Send(request, HttpCompletionOption.ResponseHeadersRead);
        await using var stream = await response.Content.ReadAsStreamAsync();
        using var reader = new StreamReader(stream);
        await Clients.Group(userId).SendAsync("answer", $">");
        while (!reader.EndOfStream)
        {
            var line = await reader.ReadLineAsync();
            if (string.IsNullOrEmpty(line))
                continue;
            await Clients.Group(userId).SendAsync("answer", $":{line}");
        }
        await Clients.Group(userId).SendAsync("answer", ".");
    }
}